<template>
  <div class="con">
    <tree @change-video="changeVideo" :ids="ids" class="treeDom" ref="treeDemo">
    </tree>
    <div class="videoDome">
      <div class="title">
        当前播放视频 > <span style="color: #7dc51e">{{ title }}</span>
      </div>
      <div
        id="element-to-record"
        style="
          border: 5px solid gray;
          border-radius: 5px;
          padding: 20px;
          margin: 20px;
          width: 480px;
          height: 360px;
        "
      >
        <video
          id="rtmpVideo"
          ref="video"
          preload="auto"
          crossorigin="*"
          autoplay="true"
          muted="muted"
          poster="@/assets/images/videoLine2.png"
        ></video>
      </div>
      <canvas
        id="background-canvas"
        width="500"
        height="300"
        style="position: absolute; top: -99999999px; left: -9999999999px"
      ></canvas>
      <p class="djs" v-show="isShow">
        {{ ntime == 0 ? "完成" : ntime + "S" }}
      </p>
    </div>
    <div class="kzdome">
      <dd class="lzv">
        <button
          class="el-icon-video-camera-solid"
          @click="recordVideo"
          :disabled="disable"
        >
          视频录制&nbsp;
        </button>
        <select v-model="value">
          <option value="15" checkd>15S</option>
          <option value="20">20S</option>
        </select>
      </dd>
      <dd class="lzv">
        <button class="el-icon-finished" @click="takpic" :disabled="disable2">
          {{ disable2 ? "抓取中 ..." : "抓取" }}
        </button>
      </dd>
      <dd class="lzv">
        <button
          :class="
            disable3 ? 'el-icon-video-pause checked' : 'el-icon-video-play '
          "
          @click="tagglePaly"
        >
          {{ !disable3 ? "启用" : "停止" }}
        </button>
      </dd>
      <dd class="lzv">
        <!-- <el-button @click="handleUserMedia">录制</el-button> -->
      </dd>
      <button id="btn-start-recording" @click="start" :disabled="adisabled">
        开启 Recording
      </button>
      <button id="btn-stop-recording" @click="stop" :disabled="bdisabled">
        停止 Recording
      </button>
    </div>
    <div style="display: block">
      <video controls autoplay playsinline id="preview-video"></video>
    </div>
    <!-- <video ref="resultVideo" controls autoplay loop /> -->
    <!-- <img ref="img" /> -->
  </div>
</template>

<script>
import RecordRTC from "recordrtc";
import flvjs from "flv.js";
import Tree from "@/components/tree";

import { Recordv, Picture, StopVideo, startVideo } from "@/http";
export default {
  name: "Video2",
  data() {
    return {
      title: "请选择监控设备",
      flvPlayer: null,
      destroyed: null,
      recorder: null,
      startTimeCutVideo: null,
      endTImeCutVideo: null,
      value: "15",
      ids: "",
      isShow: false,
      bdisabled: true,
      adisabled: false,
      ntime: 15,
      pic: "抓取",
      disable: false,
      disable2: false,
      disable3: false,
      posterSrc: require("../assets/images/loding.gif"), //require("./assets/tx.jpg"),
    };
  },
  components: {
    Tree,
  },
  mounted() {
    var skipId = window.location.search;
    if (skipId) {
      this.ids = skipId.split("=")[1];
      this.startVideo(skipId.split("=")[1]);
      setTimeout(() => {
        this.title = this.$refs.treeDemo.title;
      }, 800);
    }

    this.elementToRecord = document.getElementById("element-to-record");
    // var counter = document.getElementById("counter");
    this.canvas2d = document.getElementById("background-canvas");
    this.context = this.canvas2d.getContext("2d");
    let w = window.innerWidth;
    let h = (window.innerWidth / 16) * 9;
    this.canvas2d.width = w;
    this.canvas2d.height = h;
  },
  computed: {
    playerRef() {
      return this.$refs.video;
    },
  },

  methods: {
    async startKq() {
      let stream = await navigator.mediaDevices.getDisplayMedia({
        video: true,
      });
      console.log(stream);
      const mime = MediaRecorder.isTypeSupported("video/webm")
        ? "video/webm"
        : "video/webm;codecs=vp9";
      console.log(mime);
      let MediaRecorder = new MediaRecorder(stream, { mimeType: mime });
      let chunk = [];
      MediaRecorder.ondataavailable((e) => {
        chunk.push(e.data);
      });
      MediaRecorder.stop(() => {
        console.log("stop");
        let blob = new Blob(chunk, { type: chunk[0].type });
        let url = URL.createObjectURL(blob);
        let video = document.getElementById("preview-video");
        video.src = url;

        let a = document.createElement("a");
        a.href = url;
        a.download = "viedo.webm";
        a.click();
      });
      MediaRecorder.addEventListener("stop", function () {
        console.log(111);
      });
      MediaRecorder.start();
    },
    looper() {
      let that = this;
      if (!this.isRecordingStarted) {
        return setTimeout(this.looper, 500);
      }
      that.context.clearRect(0, 0, that.canvas2d.width, that.canvas2d.height);
      that.context.drawImage(
        that.playerRef,
        0,
        0,
        that.canvas2d.width,
        that.canvas2d.height
      );
      that.context.drawImage(
        that.playerRef,
        0,
        0,
        that.canvas2d.width,
        that.canvas2d.height
      );
      if (that.isStoppedRecording) {
        return;
      }
      requestAnimationFrame(that.looper);
    },
    start() {
      console.log(this.playerRef);
      this.isStoppedRecording = false;
      this.isRecordingStarted = true;

      this.recorder = RecordRTC(this.canvas2d, {
        type: "canvas",
      });
      this.recorder.startRecording();
      this.adisabled = true;
      this.bdisabled = false;
      document.getElementById("btn-stop-recording").disabled = false;
      this.looper();
    },
    stop() {
      let _this = this;
      this.recorder.stopRecording(function () {
        _this.isRecordingStarted = false;
        _this.isStoppedRecording = true;

        _this.bdisabled = true;
        _this.adisabled = true;
        var blob = _this.recorder.getBlob();
        document.getElementById("preview-video").src =
          URL.createObjectURL(blob);
        document.getElementById("preview-video").parentNode.style.display =
          "block";
        _this.elementToRecord.style.display = "none";

        // window.open(URL.createObjectURL(blob));
      });
    },
    // startRecording() {
    //   this.startTimeCutVideo = new Date().getTime();

    //   const canvas = this.$refs.canvas;
    //   this.recorder = RecordRTC(canvas, {
    //     type: "gif",
    //     frameRate: 200,
    //     quality: 10,
    //     disableLogs: true,
    //     onGifRecordingStarted: () => {
    //       console.log("录制开始");
    //     },
    //     onGifPreview: (gifURL) => {
    //       console.log(gifURL); // 录制中的实时数据，可以显示录制的画面
    //     },
    //   });
    //   this.recorder.startRecording(); // 开始录制
    //   this.looper(); // 循环绘制canvas
    // },
    // looper() {
    //   this.endTImeCutVideo = new Date().getTime();
    //   if ((this.endTImeCutVideo - this.startTimeCutVideo) / 1000 > 6) {
    //     this.stopRecording();
    //     return;
    //   }
    //   this.drawMedia(); // 刷新canvas
    //   requestAnimationFrame(this.looper);
    // },
    // drawMedia() {
    //   const canvas = this.$refs.canvas;
    //   const ctx = canvas.getContext("2d");
    //   const video = this.$refs.video;
    //   canvas.setAttribute("width", video.videoWidth);
    //   canvas.setAttribute("height", video.videoHeight);
    //   ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
    // },
    // stopRecording() {
    //   this.recorder.stopRecording(this.stopRecordingCallback);
    // },
    // stopRecordingCallback() {
    //   console.log("Gif 录制完成", this.recorder.getBlob());

    //   // 输出格式为video时，用vedio标签预览
    //   const video2 = this.$refs.resultVideo;
    //   video2.src = video2.srcObject = null;
    //   video2.src = URL.createObjectURL(this.recorder.getBlob());
    //   let img = this.$refs.img;
    //   img.src = URL.createObjectURL(this.recorder.getBlob());
    //   console.log(img);
    //   // 保存到本地:mkv格式，视频只有3s不知道那地方出了问题
    //   // 1
    //   // this.blobToDataURL(this.recorder.getBlob(), (dataUrl) => {
    //   //   this.saveFile(dataUrl, "capture.mp4");
    //   // });

    //   // 上传到服务器
    //   // this.upload(this.recorder.getBlob());
    //   // this.recorder.destroy();
    //   // this.recorder = null;
    // },

    // blobToDataURL(blob, callback) {
    //   var reader = new FileReader();
    //   reader.onload = function (e) {
    //     callback(e.target.result);
    //   };
    //   reader.readAsDataURL(blob);
    // },

    changeVideo(dt) {
      if (dt.nvr_state != 0) {
        this.title = dt.title;
        if (this.ids != dt.id) {
          !this.ids
            ? ((this.ids = dt.id), this.startVideo(dt.id))
            : (() => {
                this.cutoff2(this.ids).then((res) => {
                  console.log(res);
                  this.ids = dt.id;
                  this.startVideo(dt.id);
                });
              })();
        }
      } else {
        this.$message.warning("当前监控设备不在线!");
      }
    },
    startVideo(nvid) {
      startVideo({
        nvr_id: nvid,
        username: localStorage.getItem("username"),
      }).then((res) => {
        res.result_code == 200
          ? this.palyVideo(nvid)
          : this.$message.warning(res.data);
      });
    },
    palyVideo(ids) {
      if (this.flvPlayer != null) {
        // this.cutoff(this.ids);
      }
      if (flvjs.isSupported()) {
        let that = this;
        // var RVideo = this.$refs.video;
        var RVideo = document.getElementById("rtmpVideo");
        RVideo.onwaiting = function () {
          RVideo.poster = that.posterSrc;
        };
        // RVideo.controls = false;
        this.flvPlayer = flvjs.createPlayer(
          {
            type: "flv",
            cors: true,
            fluid: true,
            hasAudio: false,
            hasVideo: true,
            // duration: 6000,//总媒体持续时间，单位为毫秒
            stashInitialSize: 128, // 减少首桢显示等待时长
            url:
              "http://117.160.141.22:6055/live?port=1935&app=myapp&stream=" +
              ids,
          },
          {
            enableStashBuffer: false,
            fixAudioTimestampGap: false,
            isLive: true,
          }
        );
        this.flvPlayer.attachMediaElement(RVideo);
        this.flvPlayer.load();
        this.flvPlayer.play();
        this.disable3 = true;
        // 销毁事件
        that.destroyed = function () {
          this.flvPlayer.pause();
          this.flvPlayer.unload();
          this.flvPlayer.detachMediaElement();
          this.flvPlayer.destroy();
          this.flvPlayer = null;
        };
      } else {
        this.$message.error("浏览器不支持 > 播放失败");
      }
    },
    recordVideo() {
      // 录制视频
      if (this.ids == "") {
        this.$message.warning("请选择在线的监控设备!");
      } else {
        Recordv({ nvr_id: this.ids, recordTime: this.value })
          .then((res) => {
            console.log(res);
            if (res.result_code == 200) {
              this.disable = true;
              this.isShow = true;
              this.ntime = this.value;
              let interval = setInterval(() => {
                --this.ntime;
                if (this.ntime < 1) {
                  clearInterval(interval);
                  setTimeout(() => {
                    this.isShow = false;
                  }, 1000);
                }
              }, 1000);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    tagglePic(setTime) {
      this.disable2 = true;
      setTimeout(() => {
        this.disable2 = false;
      }, setTime);
    },
    takpic() {
      // this.$message.success("设备开始抓取!");
      // this.tagglePic(30000);
      if (this.ids == "") {
        this.$message.warning("请选择在线的监控设备!");
      } else {
        Picture({ nvr_id: this.ids }).then((res) => {
          if (res.result_code == 200) {
            this.$message.success("设备开始抓取!");
            this.tagglePic(30000);
          }
          if (res.result_code == 403) {
            this.tagglePic(15000);
            this.$message.warning("抓取中,稍后重试!");
          }
        });
      }
    },
    // 暂停与启用
    tagglePaly() {
      // this.disable3 = !this.disable3;
      if (this.disable3) {
        this.flvPlayer.pause();
        this.cutoff2(this.ids).then(() => {
          this.disable3 = false;
        });
      } else {
        if (this.ids == "") {
          this.$message.warning("请选择在线的监控设备!");
        } else if (this.flvPlayer) {
          this.flvPlayer.play();
          this.disable3 = true;
        } else {
          this.startVideo(this.ids);
        }
      }
    },
    //视频断流
    cutoff2(ids) {
      return new Promise((resolve, reject) => {
        StopVideo({ nvr_id: ids }).then((res) => {
          if (res.result_code == 200) {
            this.disable3 = false;
            this.destroyed();
            resolve("完成");
          } else {
            reject("失败");
          }
        });
      });
    },
  },
  deactivated() {
    this.flvPlayer != null ? this.cutoff2(this.ids) : "";
  },
};
</script>

<style lang="less" scoped>
#rtmpVideo {
  width: 90%;
  position: absolute;
  max-height: 58vh;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
